package com.lxb.educenter.controller;


import com.lxb.commonutils.JwtUtils;
import com.lxb.commonutils.R;
import com.lxb.commonutils.vo.UcenterMemberVO;
import com.lxb.educenter.entity.UcenterMember;
import com.lxb.educenter.entity.dto.LoginDto;
import com.lxb.educenter.entity.dto.RegisterDto;
import com.lxb.educenter.service.UcenterMemberService;
import com.lxb.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 登录与注册控制层
 *
 * @author lixuebin
 * @since 2022-12-20
 */
@Api(description = "登录与注册控制层")
@RestController
@RequestMapping("/educenter")
//@CrossOrigin
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService memberService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R loginUser(@RequestBody @Valid LoginDto loginDto, BindingResult bindingResult) {

        //LoginDto类 数据校验
        // 通过@Valid 与 实体类 注解实现数据校验
        if (bindingResult.hasErrors()) {
            return R.error().message("注册提交的参数有误," + bindingResult.getFieldError().getDefaultMessage());
        }

        //登录成功后，返回token值，使用jwt生成
        String token = memberService.login(loginDto);
        return R.ok().data("token", token);
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public R register(@RequestBody RegisterDto registerDto) {

        memberService.register(registerDto);
        return R.ok();
    }

    @ApiOperation("根据token获取用户信息")
    @GetMapping("/auth/getLoginInfo")
    public R getLoginInfo(HttpServletRequest request) {

        try {
            //调用Jwt工具，根据request对象获取请求头信息，返回用户id
            String memberId = JwtUtils.getMemberIdByJwtToken(request);

            //根据id去查询用户信息
            UcenterMember member = memberService.getById(memberId);

            return R.ok().data("userInfo", member);
        } catch (Exception e) {
            throw new GuliException(20001, "error");
        }
    }

    @ApiOperation("根据用户id获取用户信息")
    @GetMapping("/getInfoUc/{id}")
    public UcenterMemberVO getInfoUc(@PathVariable String id) {

        try {

            //根据id去查询用户信息
            UcenterMember member = memberService.getById(id);

            UcenterMemberVO memberDto = new UcenterMemberVO();
            BeanUtils.copyProperties(member, memberDto);

            return memberDto;
        } catch (Exception e) {
            throw new GuliException(20001, "error");
        }
    }

    @ApiOperation("统计某天注册人数")
    @GetMapping("/CountRegister/{day}")
    public Integer CountRegister(@PathVariable String day) {
        Integer count = memberService.CountRegister(day);
        return count;
    }
}

